package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author : qj
 * @since: 2022/10/25  17:37
 */
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Autowired
    private IKaptchaService iKaptchaService;

    @Autowired
    private IUserRegisterService iUserRegisterService;

    @PostMapping("/register")
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest request){
        String username = map.get("userName");
        String userpwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        try {
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        } catch (Exception e) {
            String message = e.getMessage();
            return new ResponseUtil<>().setErrorMsg(message);
        }
        //向用户表中插入记录
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setUserName(username);
        userRegisterRequest.setUserPwd(userpwd);
        userRegisterRequest.setCaptcha(captcha);
        userRegisterRequest.setEmail(email);
        UserRegisterResponse registerResponse = iUserRegisterService.register(userRegisterRequest);
        if (registerResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(registerResponse.getMsg());
    }
    
    /**
    * @Description 用户注册激活
    * @Author Yi
    * @Date 2022/10/27 12:12 
    */
    @GetMapping("/verify")
    public ResponseData verify (UserVerifyRequest request) {
        iUserRegisterService.verify(request);
        return new ResponseUtil<>().setData(null,"success");
    }
}
